import { Button, Card, Col, Form, Input, InputNumber, Modal, Row, Space, message } from 'antd';
import Table, { ColumnsType } from 'antd/es/table';
import { TableRowSelection } from 'antd/es/table/interface';
import { useState, useEffect } from 'react';

import commonService from '@/api/services/commonService';
import { useCommon } from '@/hooks/common';
import { toYuan, toFen } from '@/utils/format-number';

export default function AccountPage() {
  const [rechargeShow, setRechargeShow] = useState<boolean>(false);
  const [pkInfo, setPkInfo] = useState<any>({});
  const [form] = Form.useForm();

  const uri = 'member-account';
  const cateName = '资金账户';
  const {
    data = {},
    ModalPros,
    searchForm,
    onSearchFormReset,
    doDel,
    onEdit,
    onSearch,
    handleChange,
    refetch
  } = useCommon({ accountName: '', userId: '' }, uri, {
    accountName: '',
    id: 0,
    userId: '',
    status: 0,
    phoneNumber: '',
  });

  const onRechargeSubmit = () => {
    form.validateFields().then((fieldsValue: any) => {
      fieldsValue.userId = pkInfo.userId;
      fieldsValue.money = toFen(fieldsValue.money);
      commonService
        .getCustomApi('/admin/member-account/recharge', fieldsValue)
        .then(() => {
          message.success(`操作成功`);
          setRechargeShow(false);
          refetch();
        });
    });
  };

  const columns: ColumnsType<any> = [
    { title: '会员ID', dataIndex: 'userId', align: 'center', width: 60 },
    { title: '登录账号', dataIndex: 'accountName', align: 'center', width: 60 },
    // { title: '姓名', dataIndex: 'accountName', align: 'center', width: 60 },
    {
      title: '余额', dataIndex: 'balance', align: 'center', width: 60, render: (val) => {
        return toYuan(val);
      }
    },
    {
      title: '线下保证金', dataIndex: 'deposit', align: 'center', width: 60, render: (val) => {
        return toYuan(val);
      }
    },
    {
      title: '操作',
      key: 'operation',
      align: 'center',
      width: 100,
      render: (_, record) => (
        <a onClick={() => {
          setPkInfo(record);
          setRechargeShow(true);
        }}>后台充值</a>
        // <div className="flex w-full justify-center text-gray">
        //   <IconButton onClick={() => onEdit(record)}>
        //     <Iconify icon="solar:pen-bold-duotone" size={18} />
        //   </IconButton>
        //   <Popconfirm
        //     title="确认删除该数据？"
        //     okText="确定"
        //     cancelText="取消"
        //     placement="left"
        //     onConfirm={() => doDel(record.id)}
        //   >
        //     <IconButton>
        //       <Iconify icon="mingcute:delete-2-fill" size={18} className="text-error" />
        //     </IconButton>
        //   </Popconfirm>
        // </div>
      ),
    },
  ];

  // rowSelection objects indicates the need for row selection
  const rowSelection: TableRowSelection<any> = {
    onChange: (selectedRowKeys, selectedRows) => {
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    },
    onSelect: (record, selected, selectedRows) => {
      console.log(record, selected, selectedRows);
    },
    onSelectAll: (selected, selectedRows, changeRows) => {
      console.log(selected, selectedRows, changeRows);
    },
  };

  return (
    <Space direction="vertical" size="large" className="w-full">
      <Card>
        <Form form={searchForm} onFinish={onSearch}>
          <Row gutter={[16, 16]}>
            <Col span={8} lg={6}>
              <Form.Item<any> label="登录账号" name="accountName" className="!mb-0">
                <Input />
              </Form.Item>
            </Col>
            <Col span={8} lg={6}>
              <Form.Item<any> label="会员ID" name="userId" className="!mb-0">
                <Input />
              </Form.Item>
            </Col>
            <Col span={24} lg={12}>
              <div className="flex justify-end">
                <Button onClick={onSearchFormReset}>重置</Button>
                <Button type="primary" htmlType="submit" className="ml-4">
                  查询
                </Button>
              </div>
            </Col>
          </Row>
        </Form>
      </Card>

      <Card
        title={cateName}
      // extra={
      //   <div className="flex flex-row gap-[10px]">
      //     <Button
      //       type="primary"
      //       onClick={() =>
      //         onCreate({ ...formParams, parentId: query.parentId, level: query.parentId === 0 ? 1 : 2 })
      //       }
      //     >
      //       手工充值
      //     </Button>
      //   </div>
      // }
      >
        <Table
          rowKey="id"
          size="small"
          pagination={{ total: data.totalCount }}
          scroll={{ x: 'max-content' }}
          columns={columns}
          dataSource={data.list}
          rowSelection={{ ...rowSelection }}
          onChange={handleChange}
        />
      </Card>

      <CommonModal {...ModalPros} />

      <Modal
        title="后台充值"
        open={rechargeShow}
        onOk={onRechargeSubmit}
        onCancel={() => setRechargeShow(false)}
      >
        <Form
          form={form}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 18 }}
          layout="horizontal"
        >
          <Form.Item<any> label="金额" name="money" required>
            <InputNumber min={0} />
          </Form.Item>
        </Form>
      </Modal>
    </Space>
  );
}

function CommonModal({ title, show, formValue, onOk, onCancel }: any) {
  const [form] = Form.useForm();
  useEffect(() => {
    form.setFieldsValue({ ...formValue });
  }, [formValue, form]);
  return (
    <Modal
      title={title}
      open={show}
      onOk={() => onOk({ ...formValue, ...form.getFieldsValue() })}
      onCancel={onCancel}
    >
      <Form
        initialValues={formValue}
        form={form}
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 18 }}
        layout="horizontal"
      >
        <Form.Item<any> label="姓名" name="userName" required>
          <Input />
        </Form.Item>
        <Form.Item<any> label="登陆账号" name="loginName" required>
          <Input disabled />
        </Form.Item>
        <Form.Item<any> label="手机号" name="phoneNumber" required>
          <InputNumber />
        </Form.Item>
      </Form>
    </Modal>
  );
}
